<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>待办事项应用</title>
    <style>
      .editing {
        background-color: #f0f0f0;
      }
      .edit-controls {
        display: inline-block;
        margin-left: 5px;
      }
    </style>
  </head>
  <body>
    <input type="text" name="" id="ipt" placeholder="输入待办事项..." />
    <ul>
      <li>
        <span></span>
        <button>删除</button>
      </li>
    </ul>

    <script>
      let url = "http://localhost:3000/todos";
      function loadList() {
        let xhr = new XMLHttpRequest();
        xhr.open("get", url);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.send();
        xhr.onload = function () {
          if (xhr.status == 200) {
            let obj = JSON.parse(xhr.responseText);
            console.log(obj);
            document.querySelector("ul").innerHTML = obj
              .map(
                (v) => `<li>
                          <input type="checkbox" ${
                            v.completed ? "checked" : ""
                          }>
                          <span contenteditable="false" data-id="${v.id}">${
                  v.title
                }</span>
                          <div class="edit-controls" style="display: none;">
                            <button class="save" data-id="${v.id}">保存</button>
                            <button class="cancel" data-id="${
                              v.id
                            }">取消</button>
                          </div>
                          <button class="del" data-id="${v.id}">删除</button>
                        </li>`
              )
              .reverse()
              .join("");
          }
        };
      }

      loadList();

      let ipt = document.querySelector("#ipt");
      ipt.onkeydown = function (e) {
        if (e.keyCode == 13) {
          let title = ipt.value.trim();
          if (!title) return;

          let completed = false;
          let bodyObj = { title, completed };
          let xhr = new XMLHttpRequest();
          xhr.open("POST", url);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.send(JSON.stringify(bodyObj));
          xhr.onload = function () {
            if (xhr.status == 201) {
              loadList();
              ipt.value = "";
            }
          };
        }
      };

      let ul = document.querySelector("ul");
      ul.onclick = function (e) {
        const target = e.target;

        if (target.className == "del") {
          let todoId = target.dataset.id;
          let delAPI = url + "/" + todoId;
          let xhr = new XMLHttpRequest();
          xhr.open("DELETE", delAPI);
          xhr.send();
          xhr.onload = function () {
            if (xhr.status == 200) {
              loadList();
            }
          };
        } else if (
          target.tagName === "SPAN" &&
          target.getAttribute("contenteditable") === "false"
        ) {
          // 开始编辑
          const li = target.closest("li");
          target.setAttribute("contenteditable", "true");
          target.classList.add("editing");
          li.querySelector(".edit-controls").style.display = "inline-block";
        } else if (target.className === "save") {
          // 保存编辑
          const todoId = target.dataset.id;
          const span = target.closest("li").querySelector("span");
          const newTitle = span.textContent.trim();

          if (!newTitle) {
            alert("待办事项不能为空");
            return;
          }

          const updateAPI = `${url}/${todoId}`;
          const xhr = new XMLHttpRequest();
          xhr.open("PATCH", updateAPI);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.send(JSON.stringify({ title: newTitle }));
          xhr.onload = function () {
            if (xhr.status === 200) {
              span.setAttribute("contenteditable", "false");
              span.classList.remove("editing");
              target.closest(".edit-controls").style.display = "none";
            }
          };
        } else if (target.className === "cancel") {
          // 取消编辑
          const li = target.closest("li");
          const span = li.querySelector("span");
          loadList(); // 简单处理：重新加载列表，也可以保存原始值并恢复
        } else if (target.type === "checkbox") {
          // 处理完成状态
          const li = target.closest("li");
          const todoId = li.querySelector(".del").dataset.id;
          const isCompleted = target.checked;

          const updateAPI = `${url}/${todoId}`;
          const xhr = new XMLHttpRequest();
          xhr.open("PATCH", updateAPI);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.send(JSON.stringify({ completed: isCompleted }));
        }
      };
    </script>
  </body>
</html>
